package org.thunms.change.initialize.service;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javolution.util.FastList;
import javolution.util.FastMap;

import org.apache.ibatis.jdbc.ScriptRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thunms.change.initialize.model.DataInitializeScript;
import org.thunms.framework.model.DataGrid;
import org.thunms.framework.model.DataGridJson;

/**
 * 资源转换平台
 * 数据初始子系统
 * 数据初始脚本
 */
@Service
public class DataInitializeScriptService implements Serializable {
	private static final long serialVersionUID = 4207816856367969800L;
	@Autowired
	private JdbcTemplate jdbcTemplate;
	private static final Logger logger = LoggerFactory.getLogger(DataInitializeScriptService.class);
	private DataGridJson<DataInitializeScript> dataGrid = new DataGridJson<DataInitializeScript>();
	private Integer count = 0;
	private List<DataInitializeScript> rows = FastList.newInstance();
	private Map<String, Resource> scriptMap = FastMap.newInstance();

	public DataGridJson<DataInitializeScript> getDataGridList(DataGrid dg, DataInitializeScript mode) {
		try {
			if (rows.isEmpty()) {
				Resource[] rsscript = new PathMatchingResourcePatternResolver()
						.getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
								+ "/org/thunms/**/**/script/*.sql");
				for (Resource resource : rsscript) {
					StringBuffer p = new StringBuffer(resource.getURL().getPath());
					if (p.indexOf("-1.0.1-SNAPSHOT.jar!/org/thunms/") > 0) {
						p.delete(0, p.indexOf(".jar!/org/thunms/") + 5);
						String v = p.toString();
						p.delete(0, 12);
						p.reverse().delete(0, p.indexOf("/tpircs/") + 8).reverse();
						String k = UUID.randomUUID().toString();
						DataInitializeScript script = new DataInitializeScript();
						script.setScriptPath(v);
						script.setName(p.toString().replace("/", "_"));
						script.setId(k);
						rows.add(script);
						scriptMap.put(k, resource);
						count++;
					}else{
						p.delete(0, p.indexOf("/org/thunms/"));
						String v = p.toString();
						p.delete(0, 12);
						p.reverse().delete(0, p.indexOf("/tpircs/") + 8).reverse();
						String k = UUID.randomUUID().toString();
						DataInitializeScript script = new DataInitializeScript();
						script.setScriptPath(v);
						script.setName(p.toString().replace("/", "_"));
						script.setId(k);
						rows.add(script);
						scriptMap.put(k, resource);
						count++;
						
					}
				}
			}

		} catch (IOException e) {
			logger.error("解析sql脚本过程出现错误", e);
		}

		dataGrid.setRows(rows);
		dataGrid.setTotal(count.longValue());
		return dataGrid;

	}

	/**
	 * 执行脚本
	 * @param ids
	 * @return
	 */
	@Transactional(readOnly = false)
	public Boolean execute(String ids) {
		String[] keys = ids.split(",");
		for (String key : keys) {
			try {
				if(scriptMap.containsKey(key)){
					Resource rs = scriptMap.get(key);
					ScriptRunner scriptRunner = new ScriptRunner(this.jdbcTemplate.getDataSource().getConnection());
					scriptRunner.setAutoCommit(false);
					scriptRunner.runScript(new InputStreamReader(rs.getInputStream()));
					scriptRunner.closeConnection();
				}
			} catch (IOException e) {
				logger.error("脚本读取时发生错误", e);
			} catch (SQLException e) {
				logger.error("脚本执行过程出现错误", e);
			}

		}
		return true;

	}
}
